package com.supplychainapi.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.joindata.inf.common.basic.exceptions.ServiceException;
import com.supplychainapi.common.RestResponse;
import com.supplychainapi.common.enums.ExceptionMessage;
import com.supplychainapi.dao.prod.ScmTbunitMapper;
import com.supplychainapi.domain.MaterialListSearch;
import com.supplychainapi.domain.Tbunit;
import com.supplychainapi.domain.TbunitDto;
import com.supplychainapi.model.ScmTbunit;
import com.supplychainapi.param.ColTitle;
import com.supplychainapi.param.TbUnitParam;
import com.supplychainapi.service.TbUnitService;
import com.supplychainapi.utils.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;

/**
 * Created by wangziqi on 2017/9/26.
 */
@Service
public class TbUnitServiceImpl implements TbUnitService {

    @Autowired
    ScmTbunitMapper tbunitMapper;

    @Override
    public RestResponse<List<ScmTbunit>> selectActivatAll(String shopGuid) throws ServiceException {
        List<ScmTbunit> list=tbunitMapper.select(new ScmTbunit(shopGuid, (short) ExceptionMessage.is_activate.getCode()));
        if(null==list || list.isEmpty()){
            return RestResponse.success(Lists.newArrayList());
        }
        return RestResponse.success(list);
    }

    @Override
    public RestResponse save(TbUnitParam model) throws ServiceException {
        ScmTbunit tbunit=new ScmTbunit();
        BeanUtils.copyProperties(model,tbunit);
        tbunit.setFsUpdateTime(new Date());
        if(StringUtils.isBlank(tbunit.getFsUnitId())){
            tbunit.setFsUnitId(getCode(model.getFsShopGUID()));
        }
        Integer k=tbunitMapper.nameIsExit(model.getFsUnitName(),model.getFsShopGUID());
        if(k>0){
            throw  ExceptionMessage.material_name_is_exit.getServiceException();
        }
        int i =tbunitMapper.insertSelective(tbunit);
        if(i<=0){
            throw ExceptionMessage.operation_failed.getServiceException();
        }
        return RestResponse.success();
    }

    @Override
    public RestResponse update(TbUnitParam model) throws ServiceException {
        ScmTbunit tbunit=new ScmTbunit();
        BeanUtils.copyProperties(model,tbunit);
        tbunit.setFsUpdateTime(new Date());
        Integer k=tbunitMapper.nameIsExit(model.getFsUnitName(),model.getFsShopGUID());
        if(k>1){
            throw  ExceptionMessage.material_name_is_exit.getServiceException();
        }
        int i =tbunitMapper.updateByPrimaryKeySelective(tbunit);
        if(i<=0){
            throw ExceptionMessage.operation_failed.getServiceException();
        }
        return RestResponse.success();
    }

    @Override
    public RestResponse delete(List<String> list,String shopGuid) throws ServiceException {
        try {
            if(null==list || list.isEmpty()){
                throw ExceptionMessage.missing_param.getServiceException();
            }
            for (String e : list) {
                if (StringUtils.isNotBlank(e)) {
                    int a = tbunitMapper.getQuotesByTreeBuild(shopGuid, e);
                    if (a > 0) {
                        throw ExceptionMessage.delete_treebuild_failed.getServiceException();
                    }
                    ScmTbunit tbunit = new ScmTbunit();
                    tbunit.setFsUnitId(e);
                    tbunit.setFsShopGUID(shopGuid);
                    tbunitMapper.delete(tbunit);
                }
            }
        }catch (Exception e){
            throw ExceptionMessage.getSystemException(e);
        }
        return RestResponse.success();
    }

    @Override
    public RestResponse<List<TbunitDto>> selectAll(String shopGuid, MaterialListSearch search) throws ServiceException {
        PageHelper.startPage(search.getPageNum(),search.getPageSize());

        List<ScmTbunit> list = tbunitMapper.search(shopGuid, search.getKeyWords());
        List<TbunitDto> reulst=Lists.newArrayList();
        list.stream().forEach(e->{
            TbunitDto dto=new TbunitDto();
            BeanUtils.copyProperties(e,dto);
            if(dto.getFiStatus()==1){
                dto.setFiStatusName("正常");
            }
            if(dto.getFiStatus()==9){
                dto.setFiStatusName("禁用");
            }
            reulst.add(dto);
        });
        PageInfo pageInfo=new PageInfo(list);
        return RestResponse.success(pageInfo.getList(),pageInfo);
    }

    @Override
    public RestResponse<List<ScmTbunit>> selectAll(String shopGuid) throws ServiceException {
        List<ScmTbunit> list=tbunitMapper.select(new ScmTbunit(shopGuid));
        return RestResponse.success(list);
    }

    @Override
    public RestResponse<ScmTbunit> selectById(String shopGuid,String fsUnitId) throws ServiceException {
         ScmTbunit tbunit=tbunitMapper.selectByPrimaryKey(new ScmTbunit(fsUnitId,shopGuid));
         if(null==tbunit){
//             throw ExceptionMessage.no_query.getServiceException();
             return RestResponse.success();
         }
         return RestResponse.success(tbunit);
    }

    @Override
    public String getCode(String shopGuid) {
        String code= tbunitMapper.getCode(shopGuid);
//        String regEx="[^0-9]";
//        Pattern p = Pattern.compile(regEx);

        if(StringUtils.isBlank(code)){
            return "001";
        }else{
//            Matcher m = p.matcher(code);
            return StringUtil.autoGenericCode(code,code.length());
//            return StringUtil.autoGenericCode(String.valueOf(m.replaceAll(" ").trim()),m.replaceAll(" ").trim().length());
        }
    }

    @Override
    public List<ColTitle> getSchema() {
        List<ColTitle> colTitles=Lists.newArrayList();
        colTitles.add(new ColTitle("fsUnitId","计量单位代码","center",100));
        colTitles.add(new ColTitle("fsUnitName","计量单位名称","center",100));
        colTitles.add(new ColTitle("fsModelno","规格型号","center",100));
        colTitles.add(new ColTitle("fiStatusName","状态","center",100));
         colTitles.add(new ColTitle("__EDIT__", "操作", null, 150, "fsUnitId"));
        return colTitles;
    }

    @Override
    public List<ColTitle> getSelectSchema() {
        List<ColTitle> colTitles=Lists.newArrayList();
        colTitles.add(new ColTitle("fsUnitName","计量单位名称","center",100));

        return colTitles;
    }

    @Override
    public RestResponse<List<TbunitDto>> selectList(String shopGuid, MaterialListSearch search) throws ServiceException {
        PageHelper.startPage(search.getPageNum(),search.getPageSize());
        ScmTbunit param=new ScmTbunit();
        param.setFsShopGUID(shopGuid);
        param.setFiStatus((short) 1);
        List<ScmTbunit> list=tbunitMapper.select(param);
        List<TbunitDto> reulst=Lists.newArrayList();
        list.stream().forEach(e->{
            TbunitDto dto=new TbunitDto();
            BeanUtils.copyProperties(e,dto);
            reulst.add(dto);
        });
        PageInfo pageInfo=new PageInfo(list);
        return RestResponse.success(pageInfo.getList(),pageInfo);
    }

    @Override
    public RestResponse<List<Tbunit>> search(String fsShopGUID, Integer pageNum, Integer pageSize, String keyWords) throws ServiceException {
        if (null == pageNum)
            pageNum = 1;
        if (null == pageSize)
            pageSize = 20;
        PageHelper.startPage(pageNum, pageSize);
        Example example = new Example(ScmTbunit.class);
        Example.Criteria criteria = example.createCriteria().andEqualTo("fsShopGUID", fsShopGUID);
        if (StringUtils.isNotBlank(keyWords)) {
            criteria.andLike("fsUnitName", "%".concat(keyWords).concat("%"));
        }
        List<ScmTbunit> list = tbunitMapper.selectByExample(example);
        if (null == list || list.isEmpty()) {
            return RestResponse.success(Lists.newArrayList());
        }
        List list1 = Lists.newArrayList();
        list.stream().forEach(e -> {
            Tbunit tbunit = new Tbunit();
            tbunit.setFsUnitName(e.getFsUnitName());
            tbunit.setFsUnitId(e.getFsUnitId());
            tbunit.setFiStatus(e.getFiStatus());
            list1.add(tbunit);
        });
        return RestResponse.success(list1);
    }
}
